package ali;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author wxh
 */
public class Solution_17_3 {

	private static Lock LOCK = new ReentrantLock();
	private static int MAX_PRINT = 10;
	public volatile static boolean FLAG = true;

	private static CountDownLatch countDownLatch =  new CountDownLatch(2);

	public static void main(String[] args) throws InterruptedException {

		Condition conditionA = LOCK.newCondition();
		Condition conditionB = LOCK.newCondition();

		Thread threadA = new Thread(() -> {
			try {
				LOCK.lock();
				int count = 0;
				while (count < MAX_PRINT) {
					System.out.print(Thread.currentThread().getName());
					count++;
					FLAG = false;
					//把线程B从Condition队列里的fisterWait节点，移到AQS队列里
					conditionB.signal();
					if (count < MAX_PRINT) { // 如果打印完就没必要等待了，直接结束线程即可
						//1、当前线程加入到Condition队列（单向链表）
						//2、释放AQS锁，并唤醒AQS同步队列（双向链表）中的下一个节点线程
						conditionA.await();
					}
				}
				countDownLatch.countDown();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				LOCK.unlock();
			}
		});

		Thread threadB = new Thread(() -> {
			try {
				LOCK.lock();
				while (FLAG) {
					conditionB.await();
				}

				int count = 0;
				while (count < MAX_PRINT) {
					System.out.print(Thread.currentThread().getName());
					count++;
					//把线程A从Condition队列里的fisterWait节点，移到AQS队列里
					conditionA.signal();
					if (count < MAX_PRINT) {
						//1、当前线程加入到Condition队列（单向链表）
						//2、释放AQS锁，并唤醒AQS同步队列（双向链表）中的下一个节点线程
						conditionB.await();
					}
				}
				countDownLatch.countDown();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				LOCK.unlock();
			}
		});

		threadA.setName("阿");
		threadB.setName("里");

		threadA.start();
		threadB.start();

		countDownLatch.await();

		System.out.println("");
		System.out.println("执行完毕");

	}

}